import { WebSocketGateway, WebSocketServer, SubscribeMessage, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

// 定义基础数据类型接口
interface PlayerPosition {
    x: number;
    y: number;
    z: number;
}

interface PlayerRotation {
    x: number;
    y: number;
    z: number;
}
// 新增动画常量定义
const ANIMATION = {
    IDLE: "Breathing Idle",
    WALK: "Walking",
    RUN: "Standard Run"
} as const;
type AnimationType = typeof ANIMATION[keyof typeof ANIMATION];

@WebSocketGateway({ cors: { origin: '*' } })
export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {
    @WebSocketServer() server: Server;

    // 使用纯对象存储玩家状态
    private players: Record<string, {
        position: PlayerPosition;
        rotation: PlayerRotation;
        action: string;
    }> = {};

    handleConnection(client: Socket) {
        console.log(`玩家连接: ${client.id}`);

        // 初始化玩家状态（使用普通对象）
        this.players[client.id] = {
            position: { x: 0, y: 0, z: 0 },
            rotation: { x: 0, y: 0, z: 0 },
            action: 'Breathing Idle'
        };

        // 新玩家加入时发送完整状态（包含时间戳）
        client.emit('init', {
            selfId: client.id,
            players: this.players,
            serverTime: Date.now() // 同步服务器时间
        });

        // 广播给其他玩家
        client.broadcast.emit('playerConnected', {
            id: client.id,
            state: this.players[client.id]
        });
    }

    handleDisconnect(client: Socket) {
        console.log(`玩家断开: ${client.id}`);
        delete this.players[client.id];
        this.server.emit('playerDisconnected', client.id);
    }

    @SubscribeMessage('playerMove')
    handlePlayerMove(client: Socket, data: {
        position: PlayerPosition;
        rotation: PlayerRotation;
        action: string;
    }) {
        // 验证动作合法性
        const validActions = Object.values(ANIMATION);
        if (!validActions.includes(data.action as AnimationType)) {
            console.warn(`非法动作类型: ${data.action}`);
            data.action = ANIMATION.IDLE;
        }

        // 添加数据验证
        if (
            !data.position ||
            typeof data.position.x !== 'number' ||
            typeof data.position.y !== 'number' ||
            typeof data.position.z !== 'number'
        ) {
            console.warn(`无效的位置数据来自 ${client.id}`);
            return;
        }
        // 更新玩家状态（直接存储普通对象）
        this.players[client.id] = {
            position: data.position,
            rotation: data.rotation,
            action: data.action
        };

        // 广播给其他玩家
        client.broadcast.emit('playerMoved', {
            id: client.id,
            ...this.players[client.id],
            action: data.action as AnimationType,
            timestamp: Date.now() // 添加时间戳用于插值计算
        });
    }
}